package com.funny.stock.user.service.email;

import com.alibaba.fastjson.JSON;
import com.funny.stock.user.dao.pojo.UserInfoDO;
import com.funny.stock.user.service.UserInfoService;
import com.funny.stock.user.vo.MailVO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @author pengl
 * @date 2020/11/10
 */
@Component
public class MailServiceImpl implements MailService {
    private static final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);

    @Autowired
    MailProperties mailProperties;

    @Autowired
    JavaMailSenderImpl mailSender;

    @Autowired
    UserInfoService userInfoService;

    private void doSendMail(MailVO mailVO) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(mailVO.getFrom());
        simpleMailMessage.setTo(mailVO.getTo());
        simpleMailMessage.setSubject(mailVO.getSubject());
        simpleMailMessage.setText(mailVO.getText());
        mailSender.send(simpleMailMessage);
    }

    @Override
    public void sendMailToManager(MailVO mailVO) {
        mailVO.setFrom(mailProperties.getUsername());
        mailVO.setTo(mailProperties.getUsername());
        doSendMail(mailVO);
    }

    @Override
    public void sendMailToUser(MailVO mailVO, Long userInfoId) {
        UserInfoDO userInfoDO = userInfoService.queryById(userInfoId);
        if(userInfoDO == null || StringUtils.isEmpty(userInfoDO.getEmail())) {
            logger.warn("发送邮件失败，用户信息不存在或邮箱为空。{}",userInfoId);
            return;
        }

        mailVO.setFrom(mailProperties.getUsername());
        mailVO.setTo(userInfoDO.getEmail());
        logger.info("send mail:{}", JSON.toJSONString(mailVO));
        doSendMail(mailVO);
    }


}
